const express = require("express")
// 语法解析
const bodyParser = require('body-parser')
const app = express()
let multer = require('multer')
let fs = require('fs')
// 跨域
const cors = require('cors');
app.use(cors());


// 解析url编码的数据
app.use(bodyParser.urlencoded({ extended: false }));
//解析json编码数据
app.use(bodyParser.json());

// 导入数据函数
// const db = require('./config/db')


// 导入用户路由
const userRouter = require('./router/user/index.js');
app.use('/user', userRouter);

// 导入商品路由
const shopRouter = require('./router/shop/index.js');
app.use('/shop', shopRouter);
// 导入上传图片路由
// upload
const uploadRouter = require('./router/upload/index.js');
app.use('/upload', uploadRouter);

// 设置静态资源存放的路径
// http://localhost:3005/static/1.txt
app.use('/static', express.static('public'));

app.get('/', function (req, res) {
    res.send(`
        <h1>测试</h1>
      `)
})

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./public/upload/")
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + "-" + file.originalname)
    }
})

var createFolder = function (folder) {
    try {
        fs.accessSync(folder);
    } catch (e) {
        fs.mkdirSync(folder);
    }
}
var uploadFolder = './public/upload/';
createFolder(uploadFolder);
var upload = multer({
    storage: storage
});

app.post('/upload', upload.single('file'), function (req, res, next) {
    var file = req.file;
    console.log('文件类型:%s ', file.mimetype);
    console.log('原始文件名:%s ', file.originalname);
    console.log('文件大小:%s ', file.size);
    console.log('文件保存路径:%s ', file.path);
    res.json({
        res_code: '0',
        name: file.originalname,
        url: file.path
    });
});


app.listen(1018, () => {
    console.log("服务器启动 http://127.0.0.1:1018");
})